package sv.com.seguros.web.controller.asg;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import sv.com.seguros.dto.asg.AsgVenta;
import sv.com.seguros.exception.WebException;
import sv.com.seguros.web.controller.BaseController;
import sv.com.seguros.web.util.DBContext;
import sv.com.seguros.web.util.WebUtilidades;

@Controller
@RequestMapping("/ventas")
public class AsgVentaController extends BaseController {

	private static final long serialVersionUID = 3834669882649782965L;
	
	@RequestMapping(value = "/view", method = {RequestMethod.GET, RequestMethod.POST})
	public String view(ModelMap model) {
		model.put(WebUtilidades.HEADER_TITLE, "VENTAS");
		try {
			model.put("ctgTipoContactos", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllByCodigoAsArray(WebUtilidades.CTG_TIPO_CONTANTO_PADRE)));
			model.put("ctgTipoSeguros", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_TIPO_SEGUROS_PADRE)));
			model.put("isReadOnly", WebUtilidades.isReadOnly(WebUtilidades.ROLE_VENTA));
			model.put("allowDelete", WebUtilidades.isAllowDelete(WebUtilidades.ROLE_VENTA));
		} catch (WebException e) {
			logger.error("Exception:", e);
		}
		return "aseguradora/venta/asgDetalleVenta";
	}
	
	@RequestMapping(value = "/save", method = {RequestMethod.POST})
	public void save(
			@ModelAttribute("asgVenta") AsgVenta asgVenta,
			@RequestParam String ctgTipoPersonaCodigo,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			if("1".equals(ctgTipoPersonaCodigo))
				asgVenta.setCtgTipoPersona(DBContext.getCtgCatalogoDao().findByCodigo(WebUtilidades.CTG_TIPO_PERSONA_NATURAL));
			else
				asgVenta.setCtgTipoPersona(DBContext.getCtgCatalogoDao().findByCodigo(WebUtilidades.CTG_TIPO_PERSONA_JURIDICA));
			asgVenta.setSgdUsuario(WebUtilidades.getSgdUsuarioFromAcegi());
			DBContext.getAsgVentaService().save(asgVenta);
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		}catch(WebException e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		}catch(Exception e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/finalizar", method = {RequestMethod.POST})
	public void finalizar(
			@RequestParam Long asgVentaId,
			HttpServletResponse response, 
			@ModelAttribute AsgSeguroForm asgSeguroForm){
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			DBContext.getAsgVentaService().finalizar(asgVentaId);
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		}catch(WebException e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		}catch(Exception e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/findAllBy", method = {RequestMethod.POST})
	public void findAllBy(HttpServletResponse response, 
			@ModelAttribute AsgSeguroForm asgSeguroForm){
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			List<Object[]> list = DBContext.getAsgVentaDao().findAllBy(asgSeguroForm);
			result.put("totalResult", list.size());
			if(WebUtilidades.isEmptyList(list)) result.put("list", JSONArray.fromObject(list));
			else{
				result.put("list", JSONArray.fromObject(WebUtilidades.sublist(list, asgSeguroForm.getStart(), asgSeguroForm.getLimit())));
			}
			result.put(SUCCESS, true);
			result.put(MESSAGE, "Datos obtenidos");
		}catch(WebException e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		}catch(Exception e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/findByType", method = {RequestMethod.POST})
	public void findByType(
			@RequestParam Long asgVentaId,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			result.put("seguimientos", DBContext.getAsgSeguimientoDao().findAllByType(asgVentaId, "venta"));
			result.put("contactos", DBContext.getAsgContactoDao().findAllByType(asgVentaId, "venta"));
			result.put(SUCCESS, true);
			result.put(MESSAGE, "Datos obtenidos");
		}catch(WebException e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		}catch(Exception e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/deleteVenta", method = {RequestMethod.GET, RequestMethod.POST})
	public void deleteVenta(HttpServletResponse response, @RequestParam Long asgVentaId) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			DBContext.getAsgVentaService().deleteAsgVenta(asgVentaId);
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
}
